
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>


static int table[27][27] = {0};


int randchar(const int tb[27])
{
    int total = 0;
    int i;
    for (i=0; i<27; i++) {
        total += tb[i];
    }
    int d = rand() % total;
    int count = 0;
    for (i=0; i<27; i++) {
        if (d >= count && d < count + tb[i]) {
            if (i == 26)
                return -1;
            return i;
        }
        count += tb[i];
    }
    return -1;
}

unsigned int hashstring(const char * str)
{
    unsigned int len = strlen(str);
    unsigned int i;
    unsigned int total = 0;
    bool    all_numbers = true;
    for (i=0; i<len; i++) {
        total += str[i];
        if (str[i] < '0' || str[i] > '9') {
            all_numbers = false;
        }
    }
    if (all_numbers)
        return (unsigned int)atoi(str);
    return total;
}

int main(int argc, char * argv[])
{
    /*
    srand((unsigned int)time(NULL));
    int len = rand() % 7 + 3;
    int i;
    for (i=0; i<len; i++) {
        int c = rand() % 26 + 'a';
        printf("%c", c);
    }
    printf("\n");
    */

    FILE * fp = fopen("words", "rb");
    if (!fp) {
        perror("fopen");
        return -1;
    }
    memset(table, 0, sizeof(table));
    char    buffer[4096] = {0};
    while (fgets(buffer, 4096, fp) != NULL) {
        char * p = buffer + strlen(buffer);
        p--;
        while ((*p == '\r' || *p == '\n' || *p == ' ') && p >= buffer)
            p--;
        *(p + 1) = '\0';
        p = buffer;
        while (*p == ' ' || *p == '\t')
            p++;
        if (p[0] == '\0')
            continue;
        int len = strlen(p);
        int i;
        if (len == 1)
            continue;
        table[26][*p - 'a']++;
        for (i=1; i<len; i++) {
            table[*(p + i - 1) - 'a'][*(p + i) - 'a']++;
        }
        table[*(p + len - 1) - 'a'][26]++;
    }
    fclose(fp);
    /*
    int i, j;
    for (i=0; i<27; i++) {
        for (j=0; j<27; j++) {
            printf("%4d\t", table[i][j]);
        }
        printf("\n");
    }
    */

    unsigned int seed = 0;
    if (argc == 2) {
        seed = hashstring(argv[1]);
    } else {
        seed = time(NULL);
    }
    printf("seed: %u\n", seed);
    srand(seed);

    int prev = randchar(table[26]);
    int c;
    printf("%c", prev + 'a');
    if (prev != -1) {
        while ((c = randchar(table[prev])) != -1) {
            printf("%c", c + 'a');
            prev = c;
        }
    }
    printf("\n");
    return 0;
}








